package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"job-linker/cache"
	"job-linker/model"
	"strconv"
	"time"
)

func Add(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")
	if title == "" || content == "" {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "字段不可为空",
		})
		return
	}
	data := model.Position{
		Title:   title,
		Content: content,
	}
	err := model.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "添加失败",
		})
		return
	}
	var position model.Position
	redis_key := "redis_add_" + strconv.Itoa(int(position.ID))
	model.DB.Where("id = ?", data.ID).Find(&position)
	jsonData, _ := json.Marshal(position)
	cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return

}

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "5"))
	offset := (page - 1) * size
	var position []model.Position
	redis_key := "redis_list_"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Order("created_at desc").Offset(offset).Limit(size).Find(&position)
		jsonData, _ := json.Marshal(position)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &position)
	}
	var count int64
	model.DB.Model(&model.Position{}).Count(&count)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "查询成功",
		"data":  position,
		"count": count,
	})
	return
}

func Detail(c *gin.Context) {
	id := c.Query("id")
	var position model.Position
	redis_key := "redis_detail_" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Where("id = ?", id).First(&position)
		jsonData, _ := json.Marshal(position)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &position)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": position,
	})
	return
}

func Collect(c *gin.Context) {
	uid, _ := strconv.Atoi(c.Query("uid"))
	pid, _ := strconv.Atoi(c.Query("pid"))
	data := model.Collect{
		Uid: uid,
		Pid: pid,
	}
	err := model.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "收藏失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "收藏成功",
	})
	return
}
